package com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.user;

import java.util.Map;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.RandomUtil;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.concurrency.threadIt.v4.emapi.ExecutorManager;
import com.nulldev.util.data.Arrays.maps.FastMaps;

public class UserManager {

	private static final Map<String, User> USERS = FastMaps.map(64);
	private static final Runnable USER_MANAGER_MAINTAINANCE_TASK = new Runnable() {

		@Override
		public void run() {
			try {
				/* Use parallelism to speed up processing user entries. */
				USERS.entrySet().parallelStream().forEach((_user) -> {
					final User user = _user.getValue();
					if (!user.isNotBot()) {
						user.resetCaptchaStatus();
					}
					if (user.isExpired()) {
						USERS.remove(_user.getKey());
					}
				});
			} catch (Exception e) {
				JVM.errorln(e);
			}
		}
	};
	private static final Thread USER_MANAGER_MAINTAINANCE_THREAD = new Thread(new Runnable() {

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(120 * 1000L);
				} catch (InterruptedException ex0) {
				}
				ExecutorManager.get().queueTask(USER_MANAGER_MAINTAINANCE_TASK);
			}
		}
	}, "nCaptcha");

	static {
		if (!USER_MANAGER_MAINTAINANCE_THREAD.isAlive()) {
			USER_MANAGER_MAINTAINANCE_THREAD.start();
		}
	}

	public static User makeUser() {
		final String uuid = RandomUtil.quickUUID().toString();
		final User u = new User(uuid);
		USERS.put(uuid, u);
		return u;
	}

	public static User loadUserOrMake(final String uuid) {
		if (StringsUtil.isBlank(uuid)) {
			return null;
		} else if (USERS.containsKey(uuid)) {
			return USERS.get(uuid);
		} else {
			return makeUser();
		}
	}

	public static User loadUser(final String uuid) {
		return USERS.get(uuid);
	}

	public static boolean removeUser(final User user) {
		return USERS.remove(user.getUserInfoObject(UserInfoType.USER_INFO_TYPE_UUID), user);
	}

	public static boolean has(final String uuid) {
		return USERS.containsKey(uuid);
	}

	public static boolean isCaptchaComplete(final String uuid) {
		final User user = USERS.get(uuid);
		if (user == null)
			return false;
		return user.captchaDone();
	}
}
